<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小学三年级语文 - 教师试卷出题系统（讯飞X1）</title>
    <!-- 引入Bootstrap（界面美化+响应式） -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入jsPDF（PDF生成核心库） -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <!-- 引入html2canvas（将HTML转为图片，用于PDF） -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <style>
        .container { max-width: 1200px; margin: 1.5rem auto; }
        .param-card { box-shadow: 0 2px 8px rgba(0,0,0,0.08); margin-bottom: 1.5rem; }
        .paper-preview { border: 1px solid #dee2e6; padding: 2rem; margin: 1.5rem 0; background: #fff; }
        .a3-preview { max-width: 1123px; margin: 0 auto; } /* A3宽度（297mm转px约1123px） */
        .a4-preview { max-width: 794px; margin: 0 auto; } /* A4宽度（210mm转px约794px） */
        .loading { display: none; text-align: center; margin: 2rem 0; }
        .error-alert { display: none; margin: 1rem 0; }
        .print-btn-group { margin: 1rem 0; }
        .paper-header { text-align: center; margin-bottom: 1.5rem; padding-bottom: 0.5rem; border-bottom: 2px solid #333; }
        .question-section { margin-bottom: 1.2rem; }
        .question-title { font-weight: bold; margin-bottom: 0.5rem; }
        .answer-section { margin-top: 2rem; padding-top: 1rem; border-top: 1px dashed #666; }
    </style>
</head>
<body class="bg-light">
    <div class="container">
        <h3 class="text-center text-primary mb-4">小学三年级语文 - 教师试卷出题系统（讯飞X1）</h3>

        <!-- 1. 出题参数配置区 -->
        <div class="card param-card p-4">
            <h5 class="card-title text-dark mb-3">一、试卷参数配置</h5>
            <div class="row g-3">
                <!-- 出题范围 -->
                <div class="col-md-4">
                    <label class="form-label fw-semibold">出题范围（如：三年级上册第1-2单元）</label>
                    <input type="text" id="paperScope" class="form-control" value="三年级上册第1-2单元" required>
                </div>
                <!-- 题型选择（多选） -->
                <div class="col-md-4">
                    <label class="form-label fw-semibold">包含题型（可多选）</label>
                    <select id="questionTypes" class="form-select" multiple size="3" required>
                        <option value="拼音写词" selected>拼音写词</option>
                        <option value="字词辨析" selected>字词辨析</option>
                        <option value="课内阅读" selected>课内阅读</option>
                        <option value="句子仿写">句子仿写</option>
                        <option value="看图写话">看图写话</option>
                    </select>
                    <div class="form-text">按住Ctrl键可多选</div>
                </div>
                <!-- 题量配置 -->
                <div class="col-md-4">
                    <label class="form-label fw-semibold">总题量（建议10-15道）</label>
                    <input type="number" id="totalQuestions" class="form-control" min="5" max="20" value="12" required>
                    <label class="form-label fw-semibold mt-2">打印规格</label>
                    <select id="printSize" class="form-select" required>
                        <option value="A4">A4（常用）</option>
                        <option value="A3">A3（双栏排版）</option>
                    </select>
                </div>
                <!-- 难度与备注 -->
                <div class="col-md-6">
                    <label class="form-label fw-semibold">试卷难度</label>
                    <select id="paperDifficulty" class="form-select">
                        <option value="基础" selected>基础（80%基础题）</option>
                        <option value="中等">中等（60%基础+40%提升）</option>
                        <option value="提升">提升（40%基础+60%提升）</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">教师备注（如：单元测试/期中复习）</label>
                    <input type="text" id="teacherNote" class="form-control" value="单元测试卷（40分钟）">
                </div>
            </div>
            <button id="generatePaperBtn" class="btn btn-primary w-100 mt-4 py-2">生成试卷</button>
        </div>

        <!-- 2. 加载状态 -->
        <div id="loading" class="loading">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="text-muted mt-2">讯飞X1正在生成符合课标试卷，请稍候（约30秒）...</p>
        </div>

        <!-- 3. 错误提示 -->
        <div id="errorAlert" class="alert alert-danger error-alert" role="alert"></div>

        <!-- 4. 试卷预览与打印区 -->
        <div id="paperPreviewContainer" class="d-none">
            <div class="card param-card p-4">
                <h5 class="card-title text-dark mb-3">二、试卷预览（点击下方按钮打印/PDF）</h5>
                <div class="print-btn-group d-flex gap-2">
                    <button id="printBtn" class="btn btn-success">打印试卷</button>
                    <button id="exportPdfBtn" class="btn btn-info">导出PDF</button>
                    <button id="regenerateBtn" class="btn btn-outline-primary ms-auto">重新生成</button>
                </div>

                <!-- 试卷预览内容（根据A3/A4切换样式） -->
                <div id="paperPreview" class="paper-preview a4-preview mt-3">
                    <!-- 试卷标题区 -->
                    <div class="paper-header">
                        <h4 class="mb-1" id="paperTitle">小学三年级语文试卷</h4>
                        <p class="mb-0" id="paperSubtitle">三年级上册第1-2单元 · 基础卷 · 40分钟</p>
                        <p class="mb-0 text-muted" id="teacherNoteDisplay">教师备注：单元测试卷</p>
                    </div>

                    <!-- 试卷题目区（X1生成后填充） -->
                    <div id="paperQuestions" class="mb-4">
                        <!-- 示例题目结构（生成后替换） -->
                        <div class="question-section">
                            <div class="question-title">一、拼音写词（共3题，每题2分，满分6分）</div>
                            <div class="question-content ps-3">1. 看拼音写词语：chén zi（  ）<br>2. 看拼音写词语：róng máo（  ）<br>3. 看拼音写词语：yán liào（  ）</div>
                        </div>
                    </div>

                    <!-- 参考答案区（默认隐藏，点击显示） -->
                    <div class="answer-section">
                        <button id="showAnswerBtn" class="btn btn-outline-secondary">显示参考答案</button>
                        <div id="paperAnswers" class="mt-2 d-none">
                            <!-- 参考答案（X1生成后填充） -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入依赖JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 1. 讯飞X1 API配置 - 现在使用本地代理服务器
        const XUNFEI_CONFIG = {
            // API密钥由代理服务器管理
            proxyUrl: "http://127.0.0.1:5000/generate_paper"
        };

        // 2. 获取DOM元素
        const paperScope = document.getElementById('paperScope');
        const questionTypes = document.getElementById('questionTypes');
        const totalQuestions = document.getElementById('totalQuestions');
        const printSize = document.getElementById('printSize');
        const paperDifficulty = document.getElementById('paperDifficulty');
        const teacherNote = document.getElementById('teacherNote');
        const generatePaperBtn = document.getElementById('generatePaperBtn');
        const loading = document.getElementById('loading');
        const errorAlert = document.getElementById('errorAlert');
        const paperPreviewContainer = document.getElementById('paperPreviewContainer');
        const paperPreview = document.getElementById('paperPreview');
        const paperTitle = document.getElementById('paperTitle');
        const paperSubtitle = document.getElementById('paperSubtitle');
        const teacherNoteDisplay = document.getElementById('teacherNoteDisplay');
        const paperQuestions = document.getElementById('paperQuestions');
        const showAnswerBtn = document.getElementById('showAnswerBtn');
        const paperAnswers = document.getElementById('paperAnswers');
        const printBtn = document.getElementById('printBtn');
        const exportPdfBtn = document.getElementById('exportPdfBtn');
        const regenerateBtn = document.getElementById('regenerateBtn');

        // 3. 工具函数：获取选中的题型（多选处理）
        function getSelectedQuestionTypes() {
            const selected = [];
            for (let i = 0; i < questionTypes.options.length; i++) {
                if (questionTypes.options[i].selected) {
                    selected.push(questionTypes.options[i].value);
                }
            }
            return selected.join('、');
        }

        // 4. 核心：调用讯飞X1生成试卷（沿用Demo流式逻辑）
        async function generatePaperWithX1() {
            // 收集参数
            const scope = paperScope.value.trim();
            const types = getSelectedQuestionTypes();
            const count = totalQuestions.value;
            const difficulty = paperDifficulty.value;
            const note = teacherNote.value.trim();
            const printSpec = printSize.value;

            // 基础校验
            if (!scope || !types) {
                showError('请填写出题范围并选择题型');
                return;
            }

            // 状态切换
            loading.style.display = 'block';
            showError('');
            paperPreviewContainer.classList.add('d-none');

            // 构建X1请求消息（符合教师出题场景）
            const messages = [
                {
                    "role": "system",
                    "content": `你是小学三年级语文资深教师，按以下规则生成规范试卷：
1. 符合《义务教育语文课程标准》三年级要求，无超纲知识点；
2. 试卷结构：标题+副标题+题目（分题型排版，每题标分值，总分为100分）+参考答案；
3. 难度匹配：${difficulty}难度，基础题侧重课内生字词/课文理解，提升题侧重知识运用；
4. 排版要求：清晰分题型（如“一、拼音写词”“二、字词辨析”），每题单独成行，便于打印。`
                },
                {
                    "role": "user",
                    "content": `请生成小学三年级语文试卷：
- 出题范围：${scope}
- 包含题型：${types}
- 总题量：${count}道（合理分配分值，总分100分）
- 难度：${difficulty}
- 用途：${note}
- 输出格式：先试卷题目（标清题型/题数/分值），后参考答案（每题对应答案，阅读题附评分标准）。`
                }
            ];

            try {
                // 调用本地代理服务器（解决跨域问题）
                let fullPaper = "";
                const response = await fetch(XUNFEI_CONFIG.proxyUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ messages: messages }),
                    timeout: 60000 // 延长超时（试卷生成耗时较长）
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || `请求失败（HTTP ${response.status}）：${response.statusText}`);
                }

                // 处理代理服务器返回的完整响应
                const data = await response.json();
                if (!data.success || !data.content) {
                    throw new Error(data.error || '未获取到试卷内容');
                }
                
                fullPaper = data.content;

                // 解析X1返回的试卷与答案（分离题目和答案）
                const [paperContent, answerContent] = parsePaperAndAnswer(fullPaper);
                if (!paperContent) {
                    throw new Error('X1未生成有效试卷内容，请重试');
                }

                // 渲染试卷预览
                renderPaperPreview(paperContent, answerContent, scope, difficulty, note, printSpec);
                paperPreviewContainer.classList.remove('d-none');

            } catch (error) {
                let errorMsg = '试卷生成失败：';
                if (error.message.includes('401')) {
                    errorMsg += '讯飞API密钥错误，请核对Bearer密钥';
                } else if (error.message.includes('404')) {
                    errorMsg += 'X1接口地址错误或模型未开通';
                } else if (error.message.includes('timeout')) {
                    errorMsg += '生成超时，请检查网络或减少题量重试';
                } else {
                    errorMsg += error.message;
                }
                showError(errorMsg);
            } finally {
                loading.style.display = 'none';
            }
        }

        // 5. 工具函数：解析X1返回的试卷与答案（分离题目和参考答案）
        function parsePaperAndAnswer(fullContent) {
            const answerSeparator = ['参考答案', '参考答案：', '答案：', '【参考答案】'];
            let paperContent = fullContent;
            let answerContent = '无参考答案（建议重新生成）';

            // 找到参考答案分隔符，分离题目和答案
            for (const separator of answerSeparator) {
                const sepIndex = fullContent.indexOf(separator);
                if (sepIndex !== -1) {
                    paperContent = fullContent.slice(0, sepIndex).trim();
                    answerContent = fullContent.slice(sepIndex).trim();
                    break;
                }
            }

            // 格式化题目（添加HTML标签，便于排版）
            const formattedPaper = formatPaperContent(paperContent);
            const formattedAnswer = formatAnswerContent(answerContent);
            return [formattedPaper, formattedAnswer];
        }

        // 6. 工具函数：格式化试卷内容（添加题型标题、分值等HTML结构）
        function formatPaperContent(content) {
            // 按题型分割（如“一、”“二、”）
            const typeRegex = /([一二三四五六七八九十]+、[^\n]+)/g;
            let formatted = content.replace(typeRegex, (match) => `<div class="question-title">${match}</div><div class="question-content ps-3">`);
            // 闭合题型div
            formatted = formatted.replace(/<\/div>\s*<div class="question-title"/g, '</div></div><div class="question-section"><div class="question-title"');
            // 补充最后一个闭合标签
            if (formatted.includes('question-title')) {
                formatted += '</div></div>';
            }
            // 处理题目序号（如“1.”“2.”）
            formatted = formatted.replace(/(\d+、|\d+\.)/g, '<br>$1');
            return `<div class="question-section">${formatted}</div>`;
        }

        // 7. 工具函数：格式化参考答案
        function formatAnswerContent(content) {
            return content.replace(/(\d+、|\d+\.)/g, '<br>$1').replace(/参考答案/, '<h6 class="fw-bold">参考答案</h6>');
        }

        // 8. 工具函数：渲染试卷预览（切换A3/A4样式）
        function renderPaperPreview(paperContent, answerContent, scope, difficulty, note, printSpec) {
            // 更新试卷标题与副标题
            paperTitle.textContent = `小学三年级语文${note || '测试卷'}`;
            paperSubtitle.textContent = `${scope} · ${difficulty}难度 · 总分100分`;
            teacherNoteDisplay.textContent = `教师备注：${note || '无备注'}`;

            // 切换A3/A4样式
            paperPreview.className = `paper-preview ${printSpec.toLowerCase()}-preview`;
            if (printSpec === 'A3') {
                paperPreview.style.columnCount = '2'; // A3双栏排版
                paperPreview.style.columnGap = '2rem';
            } else {
                paperPreview.style.columnCount = '1'; // A4单栏
            }

            // 填充题目与答案
            paperQuestions.innerHTML = paperContent;
            paperAnswers.innerHTML = answerContent;
        }

        // 9. 工具函数：显示错误
        function showError(msg) {
            errorAlert.textContent = msg;
            errorAlert.style.display = msg ? 'block' : 'none';
        }

        // 10. PDF导出功能（基于jsPDF+html2canvas）
        async function exportToPdf() {
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF({
                orientation: printSize.value === 'A3' ? 'landscape' : 'portrait', // A3横向，A4纵向
                unit: 'mm',
                format: printSize.value // 直接使用A3/A4格式
            });

            // 将试卷预览转为图片（确保排版一致）
            const canvas = await html2canvas(document.getElementById('paperPreview'), {
                scale: 2, // 高清渲染
                useCORS: true
            });
            const imgData = canvas.toDataURL('image/jpeg', 0.95);

            // 添加图片到PDF（适配A3/A4尺寸）
            const pageWidth = printSize.value === 'A3' ? 420 : 210;
            const pageHeight = printSize.value === 'A3' ? 297 : 297;
            pdf.addImage(imgData, 'JPEG', 10, 10, pageWidth - 20, pageHeight - 20);

            // 保存PDF（文件名含年级、范围）
            const pdfFileName = `小学三年级语文-${scope.value.trim().replace(/、/g, '-')}-${new Date().toLocaleDateString()}.pdf`;
            pdf.save(pdfFileName);
        }

        // 11. 绑定事件
        // 生成试卷按钮
        generatePaperBtn.addEventListener('click', generatePaperWithX1);
        // 显示/隐藏答案
        showAnswerBtn.addEventListener('click', () => {
            paperAnswers.classList.toggle('d-none');
            showAnswerBtn.textContent = paperAnswers.classList.contains('d-none') ? '显示参考答案' : '隐藏参考答案';
        });
        // 打印按钮（调用浏览器打印）
        printBtn.addEventListener('click', () => {
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                    <head>
                        <title>${paperTitle.textContent}</title>
                        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
                        <style>.paper-preview { padding: 2rem; background: #fff; }</style>
                    </head>
                    <body>${document.getElementById('paperPreview').innerHTML}</body>
                </html>
            `);
            printWindow.document.close();
            printWindow.print();
        });
        // 导出PDF按钮
        exportPdfBtn.addEventListener('click', exportToPdf);
        // 重新生成按钮
        regenerateBtn.addEventListener('click', () => {
            paperPreviewContainer.classList.add('d-none');
            generatePaperBtn.focus();
        });
    </script>
</body>
</html>